package com.tarena.lbs.content.warm;

import com.tarena.lbs.content.dao.mapper.ArticleMapper;
import com.tarena.lbs.content.pojo.query.ArticleQuery;
import com.tarena.lbs.content.pojo.vo.ArticleVO;
import com.tarena.lbs.content.service.impl.ArticleServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;
@Slf4j
@Component
public class ArticleGeoInitializer {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleServiceImpl articleService;

    @EventListener(ApplicationReadyEvent.class)
    public void initArticleGeoData() {
        log.info("开始初始化文章地理位置数据...");

        List<ArticleVO> articles = articleMapper.selectArticleList(new ArticleQuery());
        int count = 0;

        for (ArticleVO article : articles) {
            if (article.getLongitude() != null && article.getLatitude() != null &&
                    !article.getLongitude().isEmpty() && !article.getLatitude().isEmpty()) {
                try {
                    Double longitude = Double.parseDouble(article.getLongitude());
                    Double latitude = Double.parseDouble(article.getLatitude());
                    articleService.updateArticleGeoLocation(article.getId(), longitude, latitude);
                    count++;
                } catch (NumberFormatException e) {
                    log.warn("文章经纬度格式错误 articleId: {}", article.getId());
                }
            }
        }

        log.info("文章地理位置数据初始化完成，共处理 {} 条数据", count);
    }
}